<template>
  <div id="draw-amap-container">
    <el-select v-model="searchValue" 
      id="draw-amap-search" 
      clearable 
      placeholder="输入需要检索的地址"
      filterable 
      :filter-method="selectFilter" 
      @change="selectChange" 
      value-key="full" 
      >
      <el-option v-for="item in options" :key="item.full" :label="item.full" :value="item"></el-option>
    </el-select>
    <div class="amapClass" id="draw-fence-amap" />
    <div>
      <el-row>
        <el-col :span="12">
          <el-button type="primary" @click="startDrawPolygon" v-if="'' == path || undefined == path || null == path" >新增围栏</el-button>
          <el-button type="primary" @click="startEditPolygon" v-if="showEdit && '' != path && undefined != path && null != path">编辑围栏</el-button>
          <el-button type="primary" @click="closeEditPolygon" v-if="!showEdit" >完成编辑</el-button>
          <el-button type="primary" @click="cleanFence" v-if="showEdit && '' != path && undefined != path && null != path">清除围栏</el-button>
        </el-col>
        <el-col :span="12">
          <div style="text-align:right"><font color="red">点击鼠标右键结束绘画</font></div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
const AMap = window.AMap;
export default {
  name: "AMap1",
  props: {
    initPath:{
      type:String,
      default:''
    }
  },
  data() {
    return {
      defaultCity: "厦门",
      // 地图对象
      map: null,
      // 地图标记
      marker: "",
      //搜索框地址值
      searchValue:'',
      path:'',
      //搜索框下拉选项集合
      options:undefined,
      autoitem:{},
      //围栏对象
      polyEditor: {},
      //围栏编辑标识
      showEdit: true,
      //围栏是否展示绘画开始按钮
      showStart: true,
      //中心点位（厦门）
      center: [118.08891, 24.479627],
    };
  },
  watch: {
    //加测showEdit，并传输到父级页面，通知当前绘画围栏状态
    showEdit(){
      this.$emit('setEditStatus', this.showEdit);
    },
  },
  mounted() {
    // 初始化地图页面
    this.initMap();
  },
  beforeDestroy() {
    // 销毁地图
    this.map.destroy();
  },
  methods: {
    //初始化地图页面
    initMap() {
      this.map = new AMap.Map("draw-fence-amap", {
        resizeEnable: true,
        zoom: 15,
        // mapStyle:"amap://styles/blue"
      });
      // 添加工具栏
      this.map.plugin(["AMap.ToolBar", "AMap.Scale", "AMap.HawkEye"], () => {
        // 工具条
        const toolbar = new AMap.ToolBar();
        // 比例尺
        const scale = new AMap.Scale();
        // 显示鹰眼
        // const hawkEye = new AMap.HawkEye({ isOpen: true });
        this.map.addControl(toolbar);
        this.map.addControl(scale);
        // this.map.addControl(hawkEye);
      });
      //初始化点位标记对象，用于搜索框搜索标识
      this.marker = new AMap.Marker();
      this.map.add(this.marker);

      //添加围栏对象
      this.polyEditor = new AMap.PolygonEditor(this.map);
      if('' != this.initPath && [] != this.initPath && null != this.initPath){
        var polygon = new AMap.Polygon({
          path: eval(this.initPath)
        })
        this.map.add([polygon]);
        this.polyEditor.addAdsorbPolygons([polygon]);
        this.polyEditor.setTarget(polygon);
        this.path = this.initPath;
        this.$emit('setPath', this.initPath);
      }

      // 添加检索提示
      this.addAMapAutocompletePlaceSearch();
    },
    // 添加检索提示检索
    addAMapAutocompletePlaceSearch() {
      // 自动提示
      this.map.plugin('AMap.AutoComplete', () => {
        this.autoitem = new AMap.Autocomplete({
          city: this.defaultCity,
        });
      });
    },
    // 选择自动提示数据事件回调
    selectChange(e) {
      this.searchValue = e.full;
      this.setCurrPoint(e.location.lat,e.location.lng);
    },
    //进行自动提示内容拼合
    selectFilter(val){
        let that = this;
        this.autoitem.search(val,function(status,result){
          var resultTips = result.tips.map(function(item){
              var preStr = item.district + item.address;
              if('' == preStr || undefined == preStr){
                  item.full = item.name;
              }else{
                  item.full = preStr + '-' + item.name;
              }
              return item;
          });
          that.options = resultTips;
        });
    },
    //设置点位
    setCurrPoint(lat, lon) {
      if (null != lat && undefined != lat && "" != lat && undefined != lon && null != lon && "" != lon ){
        const lnglat = [lon, lat];
        this.marker.setPosition(lnglat);
        this.map.setCenter(lnglat);
        this.map.setZoom(15);
      } else {
        this.map.setCenter(this.center);
        this.map.setZoom(15);
      }
    },
    //开始围栏绘画
    startDrawPolygon() {
      let that = this;
      if (
        that.map.getAllOverlays("polygon") == "" ||
        that.map.getAllOverlays("polygon") == [] ||
        that.map.getAllOverlays("polygon") == null
      ) {
        that.polyEditor.close();
        that.polyEditor.setTarget();
        that.polyEditor.open();
        that.showEdit = false;
      }
    },
    startEditPolygon() {
      let that = this;
      that.polyEditor.open();
      that.showEdit = false;
    },
    closeEditPolygon() {
      let that = this;
      that.polyEditor.close();
      that.showEdit = true;
      if([] != that.map.getAllOverlays("polygon") && '' != that.map.getAllOverlays("polygon") && null != that.map.getAllOverlays("polygon")){
        that.mapPath(that.map.getAllOverlays("polygon")[0].getPath());
      }else{
        that.path = '';
      }
      this.$emit('setPath', that.path);
    },
    mapPath(arr) {
      this.path = arr.map((item) => {
        return [item.lng, item.lat];
      });
    },
    cleanFence() {
      let that = this;
      var polyArr = that.map.getAllOverlays("polygon");
      that.map.remove(polyArr);
      that.path = "";
      that.showEdit = true;
      this.$emit('setPath', that.path);
    },
  },
};
</script>

<style lang="scss">
#draw-amap-container {
  #draw-fence-amap {
    height: 60vh;
    width: 100%;
    border: 1px solid #ccc;
  }
}
// .amapClass{
//   margin-left:10px;
// }
</style>